/*
 * @Author: your name
 * @Date: 2021-12-08 09:02:38
 * @LastEditTime: 2021-12-08 15:43:54
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: /vite_vue3_ts/src/utils/http/axios/axiosCancel.ts
 */

import axios, { AxiosRequestConfig, Canceler } from "axios";
import qs from "qs";
import { isFunction } from "@/utils/is/index";

/**
 * 声明一个Map用于存储每个请求的标识和取消函数
 */
let pendingMap = new Map<string, Canceler>();

/*
 *@Description: 获取请求
 *@Author: huoran
 *@Date: 2021-12-08 09:32:12
 */
export const getPendingUrl = (config: AxiosRequestConfig) =>
  [
    config.method,
    config.url,
    qs.stringify(config.data),
    qs.stringify(config.params),
  ].join("&");

export class AxiosCanceler {
  /**
   * 添加请求
   * @param config
   */
  addPending(config: AxiosRequestConfig) {
    this.removePending(config);
    const url = getPendingUrl(config);
    config.cancelToken =
      config.cancelToken ||
      new axios.CancelToken((cancel) => {
        if (!pendingMap.has(url)) {
          // 如果pending中不存在当前请求，则添加进去
          pendingMap.set(url, cancel);
        }
      });
  }

  /**
   * 移除请求
   * @param config
   */
  removePending(config: AxiosRequestConfig) {
    const url = getPendingUrl(config);

    if (pendingMap.has(url)) {
      // 如果在pending中存在当前请求标识，需要取消当前请求，并且移除
      const cancel = pendingMap.get(url);
      cancel && cancel(url);
      pendingMap.delete(url);
    }
  }

  /**
   * 清空所有pending
   */
  removeAllPending() {
    pendingMap.forEach((cancel) => {
      cancel && isFunction(cancel) && cancel();
    });
    pendingMap.clear();
  }

  /**
   * 重置
   */
  reset(): void {
    pendingMap = new Map<string, Canceler>();
  }
}
